﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using System.Configuration;
using System.Xml.Linq;
using Newtonsoft.Json.Linq;
using DZH.TextSearch.Model;

namespace DZH.TextSearch.BLL
{
    public class Query
    {
        public static IList<SearchResultModel> QueryBy(string c2, string key, ref PagerModel pager)
        {
            IList<SearchResultModel> f = null;

            string url = ConfigurationManager.AppSettings["SearchUrl"];

            if (c2 != "0")
            {
                key += string.Format(" AND C2 ({0})", c2);
            }
            pager.PageSize = 30;
            string postUrl = string.Format(url, key, pager.PageSize, pager.Skip);

            string result = DataAccess.HttpPost(postUrl, "");

            JObject data = (JObject)JsonConvert.DeserializeObject(result);

            JToken response = data["response"];
            if (response != null)
            {
                JToken num = response["numFound"];
                pager.DataCount = num.Value<long>();
                pager.CurrPageID = response["start"].Value<int>() / pager.PageSize;

                if (pager.DataCount > 0)
                {
                    string json = response["docs"].ToString();
                    f = JsonConvert.DeserializeObject<List<SearchResultModel>>(json);

                    JToken[] arrhl = data["highlighting"].ToArray<JToken>();

                    for (int i = 0; i < f.Count; ++i)
                    {
                        f[i].C3 = arrhl[i].First.First.First.ToObject<JArray>()[0].Value<string>().Trim();
                        f[i].C15c = arrhl[i].First.Last.First.ToObject<JArray>()[0].Value<string>().Trim();
                    }
                }
            }

            return f;
        }
    }
}
